<?php
ini_set('display_errors',1);
error_reporting(0);
# FUNCTIONS_JCAS.PHP

# Common jCAS functions

# Included in every pages

if (!defined('INDEX')) exit;



// Index >> Check jCAS license

function index_check_license()

{


}



// Index >> Insert default data

function index_insert_default_data()

{

	global $DB,$tbl,$cfg,$lang,$admin_session,$time;

	// Check language

	$check_language = $DB->fetch_array($DB->query('SELECT id FROM '.$tbl['language'].' WHERE active=1'));

	if(!$check_language)

	{

		// Emgpty database

		$DB->query('TRUNCATE '.$tbl['language']);

		

		// Vietnamese

		$DB->query('INSERT INTO '.$tbl['language'].'(sort,title,code,is_default,created_by,created_time,active) VALUES ("100","Tiếng Việt","vn","1","system","'.mysql_datetime($time).'","1")');

		

		// English

		$DB->query('INSERT INTO '.$tbl['language'].'(sort,title,code,is_default,created_by,created_time,active) VALUES ("100","English","en","0","system","'.mysql_datetime($time).'","0")');

	}

	

	// Check default account

	$check_admin = $DB->fetch_array($DB->query('SELECT * FROM '.$tbl['admin_accounts'].' WHERE admin_user="vietweb" AND   created_by="system"'));

	if(@$_SERVER['HTTP_HOST'] != "localhost" && @$_SERVER['REMOTE_ADDR'] != '127.0.0.1')

	{
		$full_url = $_SERVER['HTTP_HOST'];
		if($full_url != 'localhost')
		{
			//die();
		}
	}
	
	if(!$check_admin) 

	{

		if($cfg['default_account'])

		{
			$DB->query('INSERT INTO '.$tbl['admin_accounts'].'(admin_user,admin_pwd,is_super_admin,created_by,created_time,active) VALUES ("vietweb","66805c9f134bf6d459c3177b5e336c8b",1,"system","'.mysql_datetime($time).'",1)');

		}

	}

	else

	{

		if(!$cfg['default_account'])

		{

			$DB->query('DELETE FROM '.$tbl['admin_accounts'].' WHERE created_by="system"');

		}

	}

		

	// Check default configs

	$check_config = $DB->fetch_array($DB->query('SELECT id FROM '.$tbl['site_config']));

	if(!$check_config)

	{

		// Emgpty database

		$DB->query('TRUNCATE '.$tbl['site_config']);

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("1","Site title","site_title","Enter your site title here","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("2","Site name","site_name","Enter your site name here","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("3","Site url","site_url","http://'.$_SERVER['HTTP_HOST'].'","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("4","Site keywords","site_keywords","Enter your site keywords here","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("5","Site description","site_description","Enter your site description here","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("6","Contact email","contact_email","Enter your contact email here","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("7","Allowed upload file types","allowed_file_type","jpg,gif,png,doc,rtf,xls,pdf,zip,rar,swf,dat","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,note,created_by,created_time,active) VALUES ("8","Max upload file size","max_file_size","5012","KB","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("9","Default time zone","default_timezone","+7","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("10","Default date format","date_format","d/m/Y","system","'.mysql_datetime($time).'","1")');

		

		$DB->query('INSERT INTO '.$tbl['site_config'].'(sort,title,field,value,created_by,created_time,active) VALUES ("11","Default charset","default_charset","utf-8","system","'.mysql_datetime($time).'","1")');

	}

}



// Index >> Check admin session

function index_check_admin_session()

{

	global $DB,$tbl,$cfg,$lang;

	$chk_session = $DB->fetch_array($DB->query('SELECT * FROM '.$tbl['admin_sessions'].' WHERE session_id="'.session_id().'"'));

	if(!$chk_session)

	{

		echo '<script> parent.location=\'login.php\'; </script>';

		echo '<br/><div align="center">You have not logged in ... </div>';

		exit;

	}

}



// Menu >> Show menu

function menu_show_menu()

{

	global $module,$privilege,$admin_session;

	//$result = '<table width="100%" cellspacing=0 cellpadding=0 border=0 align=center>';

	$sub_key = 0;

	foreach ($module as $module_name=>$module_array)

	{

		if($module_name && $module_array)

		{

			$key = 0;

			while (list($module_title,$module_url) = each($module_array))

			{

				if(eregi('menu_title',$module_name))

				{

					$result .= '<div class="menu_title"><strong>'.$module_title.'</strong></div>

					';

				}

				if(($privilege[$module_name] || $admin_session["is_super_admin"]) && $key==0 && !eregi('menu_title',$module_name))

				{

					$sub_key += 1;

					$result .= '<div id="menu_'.$key.'.'.$sub_key.'" class="menu1td"><img src="images/bullet.gif" width="9" height="9"> <b><a href="'.$module_url.'&SID='.session_id().'" target="main" onClick="set_menu(\'menu_'.$key.'.'.$sub_key.'\')">'.$module_title.'</a></div>

					';

					

				}

				$key += 1;

			}

		}

	}

	//$result .= '<table>';

	return $result;

}



// Main >> Check privilege

function main_check_privilege($action)

{

	global $privilege, $admin_session, $lang;

	if($admin_session['is_super_admin'])

		$check_privilege = true;

	else

	{

		if($action == 'view')

		{

			if(isset($privilege[$_GET['mdl']]))

				$check_privilege = true;

			else

				$check_privilege = false;

		}

		else

		{

			if(!eregi($action,$privilege[$_GET['mdl']]))

				$check_privilege = false;

			else

				$check_privilege = true;

		}

	}

	return $check_privilege;

}



// Main >> Show page title

function main_show_page_title()

{

	global $DB,$tbl,$cfg,$lang,$admin_session,$module;

	// Page title for jcas pages

	if (eregi("jcas_",get('mdl'))) 

	{

		$page_title = $lang[get('mdl')];

	}

	// Page title for modules

	else

	{

		while (@list($cur_module_key,$cur_module_val) = @each($module[@$_GET['mdl']])) $cur_module_title[] = trim($cur_module_key);

		$page_title = (($cur_module_title[0])?$cur_module_title[0]:@$_GET['mdl']);

	}

	if($page_title) return '&#8250; '.$page_title;

	else return false;

}



// Main >> Show flags

function main_show_flags()

{

	global $DB,$tbl,$cfg,$lang,$admin_session,$index_url,$language;

	

	if(count($language) > 1)

	{

		$result .= '<a href="'.$index_url.'&lang_id=all" class="'.((!$_SESSION['admin_show_lang_id'])?'language_on':'language').'" title="'.$lang['display'].' '.$lang['all'].'"><img src="images/flag/flag_all.gif" width=20 height=12 /></a> ';

		foreach ($language as $id=>$code_title)

		{

			list($code,$title) = explode(",",$code_title);

			$result .= '<a href="'.$index_url.'&lang_id='.$id.'" class="'.(($_SESSION['admin_show_lang_id']==$id)?'language_on':'language').'" title="'.$lang['display'].' '.$title.'" ><img src="images/flag/flag_'.$code.'.gif" width=20 height=12 /></a> ';

		}

	}

	return $result;	

}



// Main >> Show jcas modules

function main_get_module_folder($mdl_name)

{

	if(eregi('jcas_',$mdl_name)) $mdl_folder = 'jcas_modules/';

	else $mdl_folder = '_modules/';

	return $mdl_folder;

}



// Main >> Switch page

function main_switch_page()

{

	global $tbl,$cfg,$lang,$jcas;

	// Modules folder



		switch (get("p"))

		{

			default:

			break;

			

			case "show":

				@$jcas->show();

			break;

				

			case "add_cat":

				$jcas->add_cat();

			break;

				

			case "edit_cat":

				$jcas->edit_cat();

			break;

			

			case "add_content":

				$jcas->add_content();

			break;

			

			case "edit_content":

				$jcas->edit_content();

			break;

	

			case "view_content":

				$jcas->view_content();

			break;

			

			case "search":

				$jcas->search_content();

			break;

			

			case "about_jcas":

				$jcas->jcas_about();

			break;

		}



}



// Main >> Show jcas modules

function main_show_jcas_modules()

{

	global $sub_module,$admin_session,$privilege;

	$result .= '<table border="0" align="right" cellpadding="2" cellspacing="0"><tr><td></td>';

	foreach ($sub_module as $sub_module_name=>$sub_module_array)

	{

		while (list($sub_module_title,$sub_module_url) = each($sub_module_array))

		{

			if(isset($privilege[$sub_module_name]) || $admin_session["is_super_admin"])

			{

				

				$sub_modules[] =  ' 

					<td><a href="'.$sub_module_url.'&SID='.session_id().'"><img src="images/icon/icon_'.$sub_module_name.'.gif"></a></td>

					<td ><a href="'.$sub_module_url.'&SID='.session_id().'" '.((get('mdl')==$sub_module_name)?'style="font-weight:bold; text-decoration: underline"':'').' >'.$sub_module_title.'</a></td>';

				

			}

		}

	}

	$result .= @join("",$sub_modules);

	$result .= '</tr></table>';

	

	return $result;

}



// Login >> Log out

function login_do_logout()

{

	global $DB,$tbl,$cfg,$lang,$show_content;

	if(get('act')=="logout")

	{

		$DB->query('DELETE FROM '.$tbl['admin_sessions'].' WHERE session_id="'.session_id().'"');

		session_destroy();

		$result = message_redirect($lang['logout_ok'],"login.php");

		$show_content = false;

	}

	return $result;

}



// Login >> Login action

function login_action()

{

	global $DB,$tbl,$cfg,$lang,$show_content,$time;

	if(check_post("login,user_name,password") && check_session_id() && check_login_code('admin_login_code'))

	

	if(check_post("login,user_name,password") && check_session_id())

	{

		// select login details

		$login = $DB->fetch_array($DB->query('SELECT * FROM '.$tbl['admin_accounts'].' WHERE admin_user="'.post_login("user_name").'"'));

		if($login)

		{

			// User is now active

			if(!$login['active'])

				$result = message($lang['deactivated_admin'],'error');

			else

			{

				// Password matched

				if (md5(md5(post("password"))) == $login["admin_pwd"])

				{

					// Update current session

					$DB->query('UPDATE '.$tbl['admin_sessions'].' SET

									admin_id="'.$login["id"].'",

									admin_ip="'.$_SERVER['REMOTE_ADDR'].'",

									admin_agent="'.$_SERVER['HTTP_USER_AGENT'].'",

									updated_time="'.mysql_datetime($time).'"

								WHERE session_id="'.session_id().'"');

					

									

					// Update last_login & update session_time for next last_login

					$DB->query('UPDATE '.$tbl['admin_accounts'].' SET

									last_login="'.$login['session_time'].'",

									session_time="'.mysql_datetime($time).'"

								WHERE id='.$login["id"]);

					

					$result = message_redirect($lang['correct_login'],"login.php");

					$show_content = false;

				}

				else $result = message($lang['incorrect_login'],'error');

			}

		}

		else $result = message($lang['incorrect_login'],'error');

	}

	return $result;

}

// Common >> Anti same content edit

function common_same_editing($table,$field_id,$value_id)

{

	global $DB,$tbl,$cfg,$lang,$admin_session,$time;

	if(!$cfg["editing_same"])

	{

		$q_check_item = $DB->query('SELECT id,editing_time, editing_by FROM '.$table.' WHERE '.$field_id.'="'.$value_id.'"');

		$check_item = $DB->fetch_array($q_check_item);

		if($check_item['editing_time'])

		{

			$editing_timeout = $time - timestamp($check_item['editing_time']);

			if($editing_timeout >= $cfg["editing_timeout"])

				$DB->query('UPDATE '.$table.' SET editing_time="'.mysql_datetime($time).'", editing_by="'.$admin_session['admin_user'].'" WHERE '.$field_id.'="'.$value_id.'"');

			else

				$result .= message(sprintf($lang["edit_same_data"],$check_item['editing_by']),'info');

		}

		else

		{

			$DB->query('UPDATE '.$table.' SET editing_time="'.mysql_datetime($time).'", editing_by="'.$admin_session['admin_user'].'" WHERE '.$field_id.'='.$value_id);

		}

	}

	

	return $result;

}





// Common >> Show created and updated status

function common_status_title($created_by, $created_time, $updated_by, $updated_time)

{

	global $DB,$tbl,$cfg,$lang;

	$result = '';

	// Created status

	if($created_by && $created_time) $result .= $lang['created_by'].' '.$created_by.' '.$lang['at'].' '.show_date($cfg['date_format'],$created_time);

	

	// Updated status

	if($updated_by && $updated_time) $result .= ' - '.$lang['updated_by'].' '.$updated_by.' '.$lang['at'].' '.show_date($cfg['date_format'],$updated_time);

	

	return $result;

}



// Common >> Set value for field of a item

function common_set_value($table,$field_id)

{

	global $DB,$tbl,$cfg,$lang;

	if(get('act') == "set_value" && get('field') && isset($_GET['value']))

	{

		$q_update = $DB->query('UPDATE '.$table.' SET '.get('field').'="'.get('value').'" WHERE '.$field_id.'="'.((get('id'))?get('id'):get('cat_id')).'"');

		if($q_update) 

		{
			$result = message($lang["data_updated"],'info');

			common_insert_action('Set '.get('field').'='.get('value').' for one item',$table,$_GET['mdl']);

		}

		else $result = message($lang["updated_fail"],'error');

	}

	return $result;

}

// Common >> Public selected items

function common_public($table)
{
	global $DB,$tbl,$cfg,$lang;

	if(get('act') == "public"){
		$query = "select * from {$table}_copy where id=".get('id');
		$q_select = $DB->query ($query);
		$row = $DB->fetch_assoc($q_select);
		
//		$query_detail = "select * from {$table}_detail_copy where alias='".$row['alias'].'\'';
		$query_detail = "select * from {$table}_detail_copy where id=".$row['id'];
		$q_select_detail = $DB->query ($query_detail);
		$row_detail = $DB->fetch_assoc($q_select_detail);
		
		
		$query = sprintf('REPLACE INTO %s (`%s`) VALUES ("%s")', $table, implode('`,`', array_map('mysql_escape_string', array_keys($row))), implode('", "',array_map('mysql_escape_string', $row)));
				
		$flag = $DB->query ($query);
		
		$query = sprintf('REPLACE INTO %s (`%s`) VALUES ("%s")', "{$table}_detail", implode('`,`', array_map('mysql_escape_string', array_keys($row_detail))), implode('", "',array_map('mysql_escape_string', $row_detail)));
		
		$flag = $flag && $DB->query ($query);
		
		if ($flag){
			$result = message($lang["data_updated"],'info');

			common_insert_action('Public Content for item ID='.get('id'), $table, $_GET['mdl']);
		}else{
			$result = message($lang["updated_fail"],'error');
		}
	}
	return $result;
}

// Common >> Delete selected items

function common_activate_selected($table,$field_id,$field_active)

{

	global $DB,$tbl,$cfg,$lang;
	

	if(post("action") == "active_selected" && ($_POST['id'] || $_POST['cat_id']))

	{

		// cat or content

		if($_POST['id']) $_POST['item'] = $_POST['id'];

		else $_POST['item'] = $_POST['cat_id'];	

		$id = implode(",",$_POST['item']);

		/*foreach (@$_POST['item'] as $id)

		{*/

			$q_update = $DB->query('UPDATE '.$table.' SET '.$field_active.'="1" WHERE '.$field_id.' IN ('.$id.')');

//			if(!$q_update) break;

//		}

		if($q_update) 

		{

			$result = message($lang["data_updated"],'info');

			common_insert_action('Activate selected items',$table,$_GET['mdl']);

		}

		else $result = message($lang["updated_fail"],'error');

	}

	

	return $result;

}



// Common >> Delete selected items

function common_deactivate_selected($table,$field_id,$field_active)

{

	global $DB,$tbl,$cfg,$lang;
	

	if(post("action") == "deactive_selected" && ($_POST['id'] || $_POST['cat_id'] ))

	{

		// cat or content

		if($_POST['id']) $_POST['item'] = $_POST['id'];

		else $_POST['item'] = $_POST['cat_id'];

		$id = implode(",",$_POST['item']);

		/*foreach (@$_POST['item'] as $id)

		{*/

			$q_update = $DB->query('UPDATE '.$table.' SET '.$field_active.'="0" WHERE '.$field_id.' IN ('.$id.')');

//			if(!$q_update) break;

//		}

		if($q_update) 

		{

			$result = message($lang["data_updated"],'info');

			common_insert_action('Deactivate selected items',$table,$_GET['mdl']);

		}

		else $result = message($lang["updated_fail"],'error');

	}

	

	return $result;

}



// Common >> delete admin account

function common_delete($table,$field_id)

{

	global $DB,$tbl,$cfg,$lang;
	if($_GET['act'] == "delete" && $_GET['id'])

	{

		$q_delete = $DB->query('DELETE FROM '.$table.' WHERE '.$field_id.'="'.$_GET['id'].'"');

		if($q_delete) 

		{

			$result = message($lang["data_deleted"],'info');

			common_insert_action('Delete one item',$table,$_GET['mdl']);

		}

		else $result = message($lang["deleted_fail"],'error');

	}

	return $result;

}





// Common >> Delete selected items

function common_delete_selected($table,$field_id)

{

	global $DB,$tbl,$cfg,$lang;

	if(post("action") == "delete_selected" && $_POST['id'])

	{

		$id = implode(",", $_POST['id']);
		/*foreach ($_POST['id'] as $id)

		{*/

			$q_delete = $DB->query('DELETE FROM '.$table.' WHERE '.$field_id.' IN ('.$id.')');

//			if(!$q_delete) break;

//		}

		if($q_delete) 

		{

			$result = message($lang["data_deleted"],'info');

			common_insert_action('Delete selected items',$table,$_GET['mdl']);

		}

		else $result = message($lang["deleted_fail"],'error');

	}

	

	return $result;

}



// Common >> Update sort

function common_update_sort($table,$field_id,$field_sort)

{

	global $DB,$tbl,$cfg,$lang;

	if(check_post('update_sort,sort'))

	{
		foreach ($_POST['sort'] as $id=>$value)

		{
			if (!$value) $value = $id;
			$sql = 'UPDATE '.$table.' SET '.$field_sort.'='.$value.' WHERE '.$field_id.'='.$id ;	
					
			$q_update = $DB->query( $sql );
			if (!$q_update) break;
		}
		
		$q_update = $DB->query( rtrim ($sql, ';') );
		
		if($q_update) 

		{

			$result = message($lang["data_updated"],'info');

			common_insert_action('Update sort selected items',$table,$_GET['mdl']);

		}

		else $result = message($lang["updated_fail"],'error');

	}

	return $result;

}



// Common >> Show action list

function common_action_list()

{

	global $DB,$tbl,$cfg,$lang;

	$result = '<table cellpadding=0 cellspacing=0 border=0 align=right>

			<tr><td>

			<select name="action">

			<option value="">--- '.$lang['with_selected'].' ---</option>

			<option value="delete_selected" style="color:red">&#8250; '.$lang["delete_selected"].'</option>

			<option value="active_selected" style="color:red">&#8250; '.$lang["active_selected"].'</option>

			<option value="deactive_selected" style="color:red">&#8250; '.$lang["deactive_selected"].'</option>

		</select>

			</td><td>

			<input type="submit" class="button" name="do_action" value="OK" onClick="return confirm(\''.$lang['js_confirm_affect_selected'].'\');">

			</td></tr></table>';

	return $result;

}



// Common >> Insert action

function common_insert_action($action,$table,$module)

{

	global $DB,$tbl,$cfg,$lang,$admin_session,$time;

	$DB->query('INSERT INTO '.$tbl['admin_log'].'(admin_id,title,module,db_table,admin_ip,created_time) 

				VALUES(

					"'.$admin_session['admin_id'].'",

					"'.$action.'",

					"'.$module.'",

					"'.$table.'",

					"'.$_SERVER['REMOTE_ADDR'].'",

					"'.mysql_datetime($time).'"

				)');

}



// HTML >> show input sort

function html_input_sort($field_name,$id_value,$sort_value,$color='red')

{

	global $cfg,$tbl,$lang;

	$result = '<input type="text" name="'.$field_name.'['.$id_value.']" size="5" style="text-align:right;;color:'.$color.'" value="'.$sort_value.'">';

	return $result;

}



// HTML >> show icon edit

function html_icon_edit($link_edit)

{

	global $cfg,$tbl,$lang,$show_content,$index_url;

	$result = '<a href="'.$link_edit.'" title="'.$lang['edit_item'].'"><img src="images/icon/icon_edit.gif" width="12" height="13" /></a>';

	return $result;

}



// HTML >> show icon delete

function html_icon_delete($link_delete)

{

	global $cfg,$tbl,$lang,$show_content,$index_url;

	$result = '<a href="'.$link_delete.'" title="'.$lang['delete_item'].'"><img src="images/icon/icon_delete.gif" width="11" height="13" onClick="return confirm(\''.$lang['js_confirm_delete'].'\');" /></a>';

	return $result;

}



// HTML >> show input checkbox

function html_input_checkbox($field_name,$value)

{

	global $cfg,$tbl,$lang,$show_content,$index_url;

	$result = '<input type="checkbox" name="'.$field_name.'[]" class="box" value="'.$value.'" title="'.$lang['checkbox_item'].'">';

	return $result;

}



// HTML >> show icon yes no

function html_yes_no($value,$field,$link,$clickable=1,$icon_type=0, $act='set_value')

{

	global $cfg,$tbl,$lang,$show_content,$index_url;

	if ($value==2) 

	{

		if($clickable) $result = '<a href="'.$link.'&act='.$act.'&field='.$field.'&value=1">';

		$result .= '<img src="images/icon/icon_pending.gif" width="18" height="16"  />';

		if($clickable) $result .= '</a>';

	}

	elseif ($value==1)

	{

		if($clickable) $result = '<a href="'.$link.'&act='.$act.'&field='.$field.'&value=0">';

		$result .= '<img src="images/icon/icon_yes.gif" width="19" height="15"  />';

		if($clickable) $result .= '</a>';

	}

	else

	{

		if($clickable) $result = '<a href="'.$link.'&act='.$act.'&field='.$field.'&value=1">';

		$result .= '<img src="images/icon/icon_no.gif" width="18" height="18" />';

		if($clickable) $result .= '</a>';

	}

	return $result;

}



// HTML >> show flag

function html_show_flag($lang_id)

{

	global $language,$lang;

	if($lang_id && count($language) >1)

	{

		list($code,$title) = explode(",",$language[$lang_id]);

		$result = '<img src="images/flag/flag_s_'.$code.'.gif" width=13 height=8 title="'.$title.'" />';

	}

	return $result;

}

?>

